package com.jhf.youke.rocketmq.service;

import cn.hutool.extra.spring.SpringUtil;
import com.jhf.youke.core.utils.StringUtils;
import com.jhf.youke.rocketmq.config.RocketMqProducerConfiguration;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.DefaultMQProducer;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @Description:  生产者工厂
* @Param:
* @return:
* @Author: RHJ
* @Date: 2022/11/17
*/
@Log4j2
public class ProducerFactory {


    private static RocketMqProducerConfiguration config = SpringUtil.getBean(RocketMqProducerConfiguration.class);

    private static Map<String, DefaultMQProducer> connectionFactoryMap = new HashMap<>(64);

    /**
    * @Description:   DefaultMQProducer 不适合进行封装，每个 DefaultMQProducer 只能发送一次
    * @Param: [groupName]
    * @return: org.apache.rocketmq.client.producer.DefaultMQProducer
    * @Author: RHJ
    * @Date: 2022/11/17
    */
    public static DefaultMQProducer getDefaultMqProducer(String groupName){
        DefaultMQProducer defaultMqProducer;

        if(StringUtils.isEmpty(groupName)){
            log.error("groupName 不能为空!");
            throw new java.lang.NullPointerException("rabbitMqName为空");
        }
        if(connectionFactoryMap.containsKey(groupName)){
            defaultMqProducer = connectionFactoryMap.get(groupName);
        }else{
            defaultMqProducer = new DefaultMQProducer(groupName+ UUID.randomUUID().toString());
            defaultMqProducer.setNamesrvAddr(config.getNameServiceAddr());
            defaultMqProducer.setMaxMessageSize(config.getMaxMessageSize());
            defaultMqProducer.setSendMsgTimeout(config.getSendMsgTimeout());
            defaultMqProducer.setVipChannelEnabled(false);
            connectionFactoryMap.put(groupName, defaultMqProducer);
        }
        return defaultMqProducer;
    }

}
